package org.soma.sso.core.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpUtils {
	/**
	 * 向指定URL发送GET方法的请求
	 *
	 * @param url
	 *            发送请求的URL
	 * @param param
	 *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return URL 所代表远程资源的响应结果
	 */
	public static Map<String, List<String>> sendGet(String url, String param) {
		String result = "";
		BufferedReader in = null;
		Map<String, List<String>> map = null;
		try {
			String urlNameString = url + "?" + param;
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 建立实际的连接
			connection.connect();
			// 获取所有响应头字段
			// System.out.println(connection.getHeaderField("uname"));
			map = connection.getHeaderFields();
			// System.out.println(map.get("uname"));
		} catch (Exception e) {
			System.out.println("发送GET请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return map;
	}


	public static String sendPost(String url, List<NameValuePair> params){
		HttpPost httpPost = new HttpPost(url);
	    try {
	        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
	        CloseableHttpClient httpClient = httpClientBuilder.build();
	        RequestConfig config = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000).build();
	        httpPost.setConfig(config);
            HttpEntity httpEntity = new UrlEncodedFormEntity(params, "UTF-8");
	        httpPost.setEntity(httpEntity);
	        HttpResponse response = httpClient.execute(httpPost);
	        return EntityUtils.toString(response.getEntity());
	    }catch(Exception e){
	    	e.printStackTrace();
	    } finally {
	        httpPost.releaseConnection();
	    }
		return null;
	}

}